import React, { Component } from 'react';

import { ajax } from './common';

import _globConfig from './config';

import { Modal, Form, Avatar, Icon, Input, message, Card, Divider, Upload, Button } from 'antd';

const FormItem = Form.Item;
const Meta = Card.Meta;

const ChangePasswordCreateForm = Form.create()(
    (props) => {
        const { visible, onCancel, onCreate, form } = props;
        const { getFieldDecorator } = form;
        return (
            <Modal
                visible={visible}
                title="修改登录密码"
                okText="修改"
                onCancel={onCancel}
                onOk={onCreate}
            >
                <Form layout="horizontal">
                    <FormItem label="当前密码">
                        {getFieldDecorator('oldPsw', {
                            rules: [{ required: true, message: '请输入当前密码' }],
                        })(
                            <Input type="password" />
                        )}
                    </FormItem>
                    <FormItem label="新密码">
                        {getFieldDecorator('newPsw', {
                            rules: [{ required: true, message: '请输入新密码' }],
                        })(
                            <Input type="password" />
                        )}
                    </FormItem>
                    <FormItem label="新密码">
                        {getFieldDecorator('confirmNewPsw', {
                            rules: [{ required: true, message: '请再次输入新密码' }],
                        })(
                            <Input type="password" />
                        )}
                    </FormItem>
                </Form>
            </Modal>
        );
    }
);

class UserProfile extends React.PureComponent {
    state = {
        currentUser: null,
        changPasswordFormVisible: false,
    };

    componentDidMount() {
        ajax('SYSTEM/auth/getLoginInfo', {}, (data) => {
            //console.log(data);
            if (data !== null || data !== undefined) {
                const userInfo = {
                    userAccount: data.userAccount,
                    userId: data.userId,
                    userName: data.userName,
                    userPhoto: data.userPhoto,
                    userRoleIds: data.userRoleIds,
                };
                this.setState({ currentUser: userInfo });
            }
            else {
                this.setState({ currentUser: null });
            }
        });
    }

    showChangePasswordModal = () => {
        this.setState({ changPasswordFormVisible: true });
    }

    handleCancel = () => {
        this.setState({ changPasswordFormVisible: false });
    }

    handleCreate = () => {
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }

            if (values.newPws === values.confirmNewPws) {
                ajax('SYSTEM/ACCOUNT/changePsw', values,  (data) =>{
                    if ('success' === data) {
                        message.success("密码修改完成");
                        form.resetFields();
                        this.setState({ changPasswordFormVisible: false });
                    }
                    else {
                        message.error("修改密码失败，请联系管理员");
                    }
                });
            }
            else {
                message.error("两次输入的新密码不一致，请重新输入");
            }

        });
    }

    saveFormRef = (form) => {
        this.form = form;
    }

    handleSubmit = (e) => {

    }

    userPhotoChange = (info) => {
        if (info.file.status === 'done') {
            //const userInfo = fetchData('SYSTEM/auth/getLoginInfo', {});
           // this.setState({ currentUser: userInfo });
            //this.props.parent.setState({ currentUser: userInfo });
            this.props.parent.updateUserInfo();
            console.log(info);
        }
    }

    render() {
       
        const { currentUser } = this.state;

        if (currentUser !== null && currentUser !== undefined) {

            const { getFieldDecorator } = this.props.form;
            const formItemLayout = {
                labelCol: { span: 6 },
                wrapperCol: { span: 14 },
            };
            const confirm = () => {
                Modal.confirm({
                    title: 'some info',
                    content: 'some info',
                });
            };
            const userProfileActions = [<Icon type="key" style={{ color: '#ff7a45' }} onClick={this.showChangePasswordModal}>修改密码</Icon>];

            return (
                <div>
                    <Card title="用户信息" bordered={true} style={{ width: '100%' }} actions={userProfileActions}>
                        <Meta
                            avatar={<Avatar size="large" src={currentUser.userPhoto} />}
                            title={currentUser.userName}
                            description={currentUser.userAccount}
                        />
                        <Divider>编辑用户信息</Divider>

                        <Form onSubmit={this.handleSubmit}>
                            <FormItem
                                {...formItemLayout}
                                label="上传头像"
                                extra=""
                            >
                                {getFieldDecorator('upload', {
                                    valuePropName: 'photoFile',
                                    getValueFromEvent: this.normFile,
                                })(
                                    <Upload name="photoFile" 
                                        onChange={this.userPhotoChange} 
                                        action={_globConfig.apiBaseURL + "SYSTEM/ACCOUNT/uploadUserPhoto"} 
                                        listType="picture" 
                                        showUploadList={false}
                                        withCredentials={true}
                                        
                                    >
                                        <Button>
                                            <Icon type="upload" /> 点击上传
				                        </Button>
                                    </Upload>
                                )}
                            </FormItem>

                        </Form>
                    </Card>
                    <ChangePasswordCreateForm
                        ref={this.saveFormRef}
                        visible={this.state.changPasswordFormVisible}
                        onCancel={this.handleCancel}
                        onCreate={this.handleCreate}
                    />
                </div>
            );
        }
        else {
            return <div />;
        }
    }
}

const WrappedUserProfile = Form.create()(UserProfile);

export default WrappedUserProfile;